package main

import (
	circuit "github.com/rubyist/circuitbreaker"
	"github.com/siddontang/go/log"
	"io/ioutil"
	"time"
)

func main() {
	cb := circuit.NewThresholdBreaker(3)

	for { // for, 模拟不断地发起请求
		if cb.Ready() {
			// Breaker is not tripped, proceed
			err := doSomething()
			if err != nil {
				cb.Fail() // This will trip the breaker once it's failed 3 times
				continue
			}
			cb.Success()
		} else {
			// Breaker is in a tripped state.
			panic("Breaker is in a tripped state.")
		}
	}
}

func doSomething() error {
	client := circuit.NewHTTPClient(time.Second*2, 2, nil)
	//resp, err := client.Get("http://example.com/resource.json")
	resp, err := client.Get("http://localhost:8090/hello")
	if err != nil {
		log.Error(err)
		return err
	}
	resources, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		log.Error(err)
		return err
	}
	log.Info("body len:", len(resources))
	return nil
}
